import hashlib

import requests
from bs4 import BeautifulSoup
import hashlib
import time


def createSign(r):
    r += '0b50b02fd0d73a9c4c8c3a781c30845f'
    return hashlib.md5(r.encode("utf8")).hexdigest()

header ={
    "Referer":"https://www.baidu.com/",
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
}
keyword = input("请输入关键字:")
response = requests.get("https://music.91q.com/search?word=%s" %keyword,headers=header)
# print(response.text)

soup = BeautifulSoup(response.content,"html.parser")
# song_list = soup.find_all(name="div",class_="song-box")
page_tags = soup.find_all(name="li",class_="number")
total_page = 0
if len(page_tags) == 0:
    total_page = 1
else:
    total_page = int(page_tags[-1].string)

for cur_page in range(1,total_page+1):
    word = keyword
    appid = '16073360'
    timestamp = str(int(time.time()))
    r = 'appid=16073360&pageNo=%d&pageSize=20&timestamp=%s&type=1&word=%s' %(cur_page,timestamp ,word)
    sign = createSign(r)
    params = {
        "appid": appid,
        "timestamp": timestamp,
        "sign": sign,
        'word': word,
        "type": '1',
        'pageNo': str(cur_page),
        'pageSize': 20
    }
    response = requests.get("https://music.91q.com/v1/search", params=params)
    song_info = response.json()
    for track in song_info['data']['typeTrack']:
        TSID = track['TSID']
        song_name = track["title"]
        singer_name = ""
        for singer in track["artist"]:
            singer_name += singer['name']+"-"
        song_name = song_name.replace('""','')
        singer_name = singer_name.replace('""','')
        r = 'TSID=' + TSID + "&appid=" + appid + "&timestamp=" + timestamp
        sign = createSign(r)
        params = {
            "TSID":TSID,
            "appid":appid,
            "timestamp":timestamp,
            "sign":sign
        }
        response = requests.get("https://music.91q.com/v1/song/tracklink",params=params)
        info = response.json()
        if 'path' in info["data"]:
            response = requests.get(info["data"]["path"])
            try:
                with open('./music/%s+%s.mp3' % (singer_name, song_name), 'wb') as f:
                    f.write(response.content)
            except:
            #     处理异常的代码
                print("文件名有问题，已跳过",song_name)

            print("下载完毕"+song_name)



# name_list = soup.find_all(name="div",class_="artist ellipsis")
# for index in range(1,len(name_list)):
#     song_name = ""
#     artists = name_list[index].find_all(name="a")
#     for artists in artists:
#         song_name += artists.string + " "
#     print(song_name)


